<template>
  <ContentWrap>
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="用户标识" prop="userFlag">
        <el-select v-model="queryParams.userFlag" class="!w-240px" clearable placeholder="全部">
          <el-option :value="0" label="系统用户" />
          <el-option :value="1" label="学员用户" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" />
          重置
        </el-button>
        <!-- <el-button type="primary" plain @click="openForm('create')" v-hasPermi="['pm:user:create']">
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button> -->
        <el-button type="warning" plain @click="handleImport" v-hasPermi="['pm:user:import']">
          <Icon icon="ep:upload" /> 导入
        </el-button>
        <el-button type="success" plain @click="downloadTemplate">
          <Icon icon="ep:download" class="mr-5px" /> 模版下载
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <ContentWrap>
    <el-table v-loading="loading" :data="list">
      <el-table-column prop="userId" label="用户ID" width="100" align="center" />
      <el-table-column prop="userName" label="用户名" min-width="140" />
      <el-table-column prop="nickName" label="昵称" min-width="140" />
      <el-table-column prop="userFlag" label="用户标识" width="100" align="center">
        <template #default="scope">
          <el-tag v-if="scope.row.userFlag === 0" type="info">系统用户</el-tag>
          <el-tag v-else type="success">学员用户</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="examFlag" label="考试中" width="100" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.examFlag ? 'danger' : 'success'">{{
            scope.row.examFlag ? '是' : '否'
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="enable" label="启用" align="center" width="120">
        <template #default="scope">
          <el-switch
            v-model="scope.row.enable"
            :active-value="1"
            :inactive-value="0"
            :disabled="true"
          />
        </template>
      </el-table-column>
      <el-table-column
        prop="passwordText"
        label="登录密码"
        show-overflow-tooltip
        width="180"
        align="center"
      />
      <el-table-column
        prop="createTime"
        label="创建时间"
        width="180"
        align="center"
        :formatter="dateFormatter"
      />
      <el-table-column label="任务" width="140" align="center">
        <template #default="scope">
          <span v-if="!scope.row.tasks || scope.row.tasks.length === 0">-</span>
          <el-button v-else link type="primary" @click="openTasks(scope.row)"
            >{{ scope.row.tasks.length }} 个</el-button
          >
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="160">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row)"
            v-hasPermi="['pm:user:update']"
            >编辑</el-button
          >
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row)"
            v-hasPermi="['pm:user:delete']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：新增/编辑（本地） -->
  <UserForm ref="formRef" @success="getList" />

  <UserImportForm ref="importFormRef" @success="getList" />

  <UserTasksDialog ref="tasksRef" />
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import * as PmUserApi from '@/api/pm/user'
import UserForm from './UserForm.vue'
import UserImportForm from './UserImportForm.vue'
import UserTasksDialog from './UserTasksDialog.vue'

defineOptions({ name: 'PmUser' })

const message = useMessage()
const loading = ref(true)
const total = ref(0)
const list = ref<any[]>([])
const queryFormRef = ref()
const formRef = ref()
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  userFlag: undefined as undefined | 0 | 1
})

// 获取列表
const getList = async () => {
  loading.value = true
  try {
    const res = await PmUserApi.getUserPage({
      page: queryParams.pageNo,
      limit: queryParams.pageSize,
      userFlag: queryParams.userFlag
    })
    list.value = res.list
    total.value = res.total
  } finally {
    loading.value = false
  }
}

// 搜索
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

// 重置
const resetQuery = () => {
  Object.assign(queryParams, { pageNo: 1, pageSize: 10, userFlag: undefined })
  getList()
}

// 模版下载（无权限限制）
const downloadTemplate = async () => {
  const res = await PmUserApi.importUserTemplate()
  download.excel(res as unknown as Blob, '用户导入模版.xls')
}

// 导入
const importFormRef = ref()
const handleImport = () => {
  importFormRef.value.open()
}

// 打开新增/编辑
const openForm = (mode: 'create' | 'update', row?: any) => {
  ;(formRef.value as any)?.open(mode, row)
}

const handleDelete = async (row: any) => {
  try {
    await message.delConfirm()
    await PmUserApi.deleteUser(row.userId)
    message.success('删除成功')
    await getList()
  } catch {}
}

const openTasks = (row: any) => {
  ;(tasksRef.value as any)?.open(row.tasks || [])
}

const tasksRef = ref()

onMounted(() => {
  getList()
})
</script>
